#include "header.h"
#include "myepoll.hpp"
#include "timerfd.hpp"
#include "thread.hpp"
#include <iostream>
#include <stdio.h>
#include <unordered_map>
#include <chrono>
#include <sys/timerfd.h>
#include "tcpconnection.hpp"
#include "socket.hpp"
#include "socketio.hpp"
#include "acceptor.hpp"
using namespace std;
using std::unordered_map;
#define BUFFER_SIZE 1024
struct client_t{//存储建立好的链接的相关消息
    int fd;//存储客户的文件描述符
    time_t last_time;//存储客户的最后一次活跃时间
};
namespace moqi
{
int test()
{
//    const char * sourceIP = "0.0.0.0";
  //  const char * sourcePort = "9031";
    Acceptor acceptor(9031);
    acceptor.ready(); 
    
    int listenfd = acceptor.getSockFd();
    MyEpoll epoll;//创建epoll对象

    unordered_map<int, time_t> clients;//用来存储客户的相关信息，key为文件描述符，time_t为最后发送时间
    epoll.add(listenfd, EPOLLIN, [&,listenfd](uint32_t events){
              if(events&EPOLLIN){//全连接到来事件
              int clientfd = acceptor.accept();
              if(clientfd != -1){
                  clients[clientfd] =std::time(nullptr);
                  printf("new connect come\n");
                  TcpConnection connect(clientfd);
                  cout << connect.status() << endl;
                  printf("此时有%ld个客户\n",clients.size());
                  cout<<"客户套接字是"<<clientfd<<endl;
                  epoll.add(clientfd, EPOLLIN | EPOLLET, [&](uint32_t events){
                            cout<<"读事件触发"<<endl;
                        if(events&EPOLLIN){
                            char buffer[BUFFER_SIZE];
                            int count = recv(clientfd, buffer, sizeof(buffer),0);//接收用户发过来的数据
                            if (count > 0) {
                                clients[clientfd] =std::time(nullptr);
                                // 回显数据
                                printf("客户%d发来%d字节数据 ：%s\n", clientfd, count, buffer);
                                fflush(stdout); // 确保提示信息立即显示
                                for(auto it = clients.begin();it != clients.end(); ++it){
                                string from;
                                from+=clientfd+'0';
                                from+=" : ";
                                from +=string(buffer);
                                    if(clientfd!=it->first){
                                      connect.send(from);  
                                      //此处！！！！！！不要把first写成second
                                        }
                                }
                            } else if (count == 0 || (count == -1 && errno != EAGAIN)) {
                                // 连接关闭或出错
                                cout << connect.status()<<"closed" << endl;
                                epoll.del(clientfd);
                                close(clientfd);
                            }
                            
                        }//end of if evevt&EPOLLIN
                        });//end of add clientfd 
              }//end of if clientfd !=-1
              }//end of if event&EPOLLIN
    });//end of add listenfd

    TimerFd timefd(1, 2,[&clients, &epoll](){
            cout<<"定时器到时"<<endl;
            int curTime = time(nullptr);
            for(auto client:clients)
            //TO DO//迭代器失效，不能用AutoCode
            {
                if(curTime-client.second > 30)
                {
                    int delfd = client.first;
                    close(delfd);
                    cout << "客户" << "超时踢出" << endl;
                    cout << "上次发言时间 ："<< client.second << endl;
                    cout << "当前时间： " << curTime << endl;
                    clients.erase(delfd);
        //            epoll.del(delfd);
                }
            }
            });
 
    moqi::Thread th(bind(&TimerFd::start, &timefd));
    th.start();
    while(1){
        epoll.wait(5000);
    };
}
}//end of namespace moqi
 
int main()
{
    moqi::test();
    return 0;
}
